import 'package:flutter/material.dart';
import 'package:async/src/async_memoizer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flowerny/model/good.dart';
import 'package:dio/dio.dart';
import 'package:flowerny/base/config/conf_web.dart';
import 'reward_item.dart';

class Reward extends StatefulWidget {
  @override
  State createState() {
    return ChatState();
  }
}

class ChatState extends State<Reward> with AutomaticKeepAliveClientMixin {
  List<Good> _goodsList = [];
  RefreshController _refreshController;
  final AsyncMemoizer _memoizer = AsyncMemoizer();

  _getGoodsList() {
    return _memoizer.runOnce(_fetchList);
  }

  _fetchList() async {
    try {
      final response = await Dio().get('${Config.BASE_URL}/goods/get_goods');
      if (response.statusCode == 200) {
        print(response.toString());
        _goodsList = Good.fromJson(response.toString());
      }
    } catch (e) {
      print(e.toString());
    }
    setState(() {
      _refreshController.refreshCompleted();
    });
    return _goodsList;
  }

  @override
  void initState() {
    super.initState();
    _refreshController = new RefreshController();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        centerTitle: true,
        brightness: Brightness.dark,
        title: Text(
          '赏金',
          style: TextStyle(
            fontSize: 20.0,
            color: Colors.white,
          ),
        ),
      ),
      body: _getList(),
    );
  }

  Widget _getList() {
    return Center(
      child: FutureBuilder(
        future: _getGoodsList(),
        builder: (context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
            case ConnectionState.waiting:
              return CircularProgressIndicator();
            default:
              if (snapshot.hasError) {
                return Text('Error:${snapshot.error}');
              } else {
                return _createListView(context, snapshot);
              }
          }
        },
      ),
    );
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      isNestWrapped: false,
      header: WaterDropHeader(),
      onRefresh: () {
        _fetchList();
      },
      child: ListView.builder(
        key: PageStorageKey('list-mession'),
        itemCount: _goodsList.length,
        itemBuilder: _buildGoodsItem,
      ),
    );
  }

  Widget _buildGoodsItem(BuildContext context, int index) {
    Good good = _goodsList[index];
    return RewardItem(good);
  }
}
